package com.wrial.kind.doublepointer;
/*
 * @Author  Wrial
 * @Date Created in 14:07 2020/8/14
 * @Description 合并 k 个排序链表，返回合并后的排序链表。请分析和描述算法的复杂度。
 */

public class MergeKLists {
    /**
     * 1.for循环然后每次紧挨着的两个进行合并  时间复杂度为  k*k*n（k为链表个数，n为每个最大的链表长度）  空间为O(k)也可以为O(1)
     * 2.分治法
     * 3.优先队列
     */
    /*
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) return null;
        ListNode ans = null;
        for (int i = 0; i < lists.length; i++) {
            ans = mergeLists(ans, lists[i]);
        }
        return ans;
    }


     */
    private ListNode mergeLists(ListNode l1, ListNode l2) {
        ListNode node = new ListNode(-1);
        ListNode p = node;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                p.next = l1;
                l1 = l1.next;
            } else {
                p.next = l2;
                l2 = l2.next;
            }
            p = p.next;
        }
        p.next = l1 == null ? l2 : l1;
        return node.next;
    }


    /**
     *  分治法，可以将lists先分再和   先merge 再sort，然后递归两两合并
     *  时间复杂度为O(n*klogk)    空间O(logk)
     */
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) {
            return null;
        }
        return merge(lists, 0, lists.length-1);

    }

    private ListNode merge(ListNode[] lists, int left, int right) {
        if (left==right) return lists[left];
            int mid = (left+right)/2;
            ListNode l = merge(lists, left, mid);
            ListNode r = merge(lists, mid + 1, right);
            return mergeLists(l,r);
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

}
